package api

import (
	"github.com/gin-gonic/gin"
	"service"
	"pojo/form"
	"constant"
	"pojo/vo"
	"net/http"
	"strconv"
)

type AdminApi struct {
	service *service.AdminService
}

// 创建AdminApi
func NewAdminApi(service *service.AdminService) *AdminApi {

	return &AdminApi{
		service: service,
	}
}

// 查询管理员列表
func (this *AdminApi) List(ctx *gin.Context) {

	query := &form.AdminPageQueryForm{}
	ctx.Bind(query)

	result := this.service.QueryAdmins(query)

	ctx.JSON(http.StatusOK, result)
}

// 管理员登录
func (this *AdminApi) Login(ctx *gin.Context) {

}

// 新增管理员信息
func (this *AdminApi) Insert(ctx *gin.Context) {

	adminForm := &form.AdminForm{}

	var result vo.Base

	err := ctx.Bind(adminForm)

	if err != nil { // 绑定参数出现错误
		result = constant.ARGUMENTS_BIND_ERROR
		result.Info = err.Error()

		ctx.JSON(http.StatusOK, result)
		return
	}

	// 参数验证
	ok, err := adminForm.Validate()

	if !ok { // 验证不通过
		result = constant.ARGUMENTS_VALIDATE_ERROR
		result.Info = err.Error()
		ctx.JSON(http.StatusOK, result)
		return
	}

	// 验证通过
	_, err = this.service.InsertAdmin(adminForm)
	if err != nil { // 保存失败
		result = constant.SERVICE_ERROR
		result.Info = err.Error()
	} else {
		result = constant.SUCCESS
	}

	ctx.JSON(http.StatusOK, result)
}

// 修改管理员信息
func (this *AdminApi) Update(ctx *gin.Context) {

	adminForm := &form.AdminForm{}

	var result vo.Base

	err := ctx.Bind(adminForm)

	if err != nil { // 绑定参数出现错误
		result = constant.ARGUMENTS_BIND_ERROR
		result.Info = err.Error()

		ctx.JSON(http.StatusOK, result)
		return
	}

	_, err = this.service.UpdateAdmin(adminForm)

	if err != nil { // 保存失败
		result = constant.SERVICE_ERROR
		result.Info = err.Error()
	} else {
		result = constant.SUCCESS
	}

	ctx.JSON(http.StatusOK, result)
}

// 删除管理员信息
func (this *AdminApi) Delete(ctx *gin.Context) {

	id, _ := strconv.ParseUint(ctx.Param("id"), 10, 64)

	err := this.service.DeleteAdmin(id)

	var result vo.Base

	if err != nil {
		result = constant.SERVICE_ERROR
		result.Info = err.Error()
		result.Msg = "删除管理员失败"
	} else {
		result = constant.SUCCESS
	}

	ctx.JSON(http.StatusOK, result)
}
